package cn.itcast.crm.service.impl;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.dao.CustomerDao;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;

@Service // 交由spring管理
@Transactional // 添加事务管理
public class CustomerServiceImpl implements CustomerService {

	// 注入dao层
	@Autowired
	private CustomerDao customerDao;

	@Override
	public List<Customer> findNoAssociationCustomer() {
		// 运用jpaRespository的规定命名格式
		return customerDao.findByFixedAreaIdIsNull();
	}

	@Override
	public void associateCustomerToFixedArea(String customerIdStr, String fixedAreaId) {
		//将客户关联到定区，会涉及到将一些客户从右边的定区客户移除到左边的未绑定定区的客户中，此时我们在进行绑定客户的时候需要先将所有关联到该定区的客户解绑
		customerDao.clearAssociatedCustomer(fixedAreaId);
		//System.out.println(StringUtils.isBlank(customerIdStr));
		//System.out.println(customerIdStr);
		// 这里传递过来客户的参数在一个以上，我们用，进行切割，得到每一个客户具体的id
		if (StringUtils.isBlank(customerIdStr)) {

			
			return;
			

			}else{
				String[] ids = customerIdStr.split(",");
				for (String id : ids) {
					// 这里客户的id应该是int类型的
					customerDao.associateCustomerToFixedArea(fixedAreaId, Integer.parseInt(id));	
			}
		}

	}

	@Override
	public List<Customer> findAssociatedCustomer(String fixedAreaId) {
      System.out.println("定区id"+fixedAreaId);
		return customerDao.findCustomerByfixedAreaId(fixedAreaId);
	}

	@Override
	public void saveCustomer(Customer customer) {
		customerDao.save(customer);
		
	}

	@Override
	public Customer findByTelephone(String telephone) {
		
		return customerDao.findByTelephone(telephone);
	}

	@Override
	public void updateType(String telephone) {
		
		customerDao.updateType(telephone);
	}

	@Override
	public Customer findCustomerByTelephoneAndPassword(String telephone, String password) {
		Customer customer = customerDao.findCustomerByTelephoneAndPassword(telephone,password);
		return customer;
	}

	@Override
	public String findFixedAreaIdByAddress(String address) {
		
		return customerDao.findFixedAreaIdByAddress(address);
	}

}
